// 输入: nums = [-1,0,3,5,9,12], target = 9
// 升序，不重复 nums 找到target 的位置，没有返回-1
// 二分法的前提是 数组有序且不重复

const nums=[-1,0,1,3,5,9,12]

// 左闭右闭
// function Dichotomy(target,arry) {
//   let left1 = 0
//   let right1 = arry.length - 1
//   return function recursion(left=left1, right=right1) {
//     // console.log(left,right)
//     if (left <= right) {
//       let middle = Math.floor((right + left) / 2)
//       // console.log(middle)
//       if (target < arry[middle]) {
//         right = middle - 1
//         return recursion(left,right)
//       } else if (target>arry[middle]) {
//         left = middle + 1
//         return recursion(left,right)
//       } else if(target==arry[middle]) {
//         return middle
//       }
//     } else {
//       return -1
//     }
//   }
// }

// 左闭右开
function Dichotomy(target,arry) {
  let left1 = 0
  let right1 = arry.length
  return function recursion(left=left1, right=right1) {
    console.log(left,right)
    if (left < right) {
      let middle = Math.floor((right + left) / 2)
      // console.log(middle)
      if (target < arry[middle]) {
        right = middle
        return recursion(left,right)
      } else if (target>arry[middle]) {
        left = middle+1
        return recursion(left,right)
      } else if(target==arry[middle]) {
        return middle
      }
    } else {
      return -1
    }
  }
}

let fun = Dichotomy(7, nums)
console.log(fun())